package com.zk.api.export;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zk.api.model.ClassModel;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class ExportDoc {

	private Configuration configuration;
	private String encoding;

	public ExportDoc(String encoding) {
		this.encoding = encoding;
		configuration = new Configuration(Configuration.VERSION_2_3_28);
		configuration.setDefaultEncoding(encoding);
		configuration.setClassForTemplateLoading(this.getClass(), "/com/zk/api");// configuration.setBooleanFormat("true,false");
		// configuration.setClassicCompatible(true);
	}

	public Template getTemplate(String name) throws Exception {
		return configuration.getTemplate(name, encoding);
	}

	public static Map<String, Object> getDataMap() {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		List<ClassModel> clazzs = new ArrayList<ClassModel>();
		return dataMap;
	}

	public void exportDoc(OutputStream os, String name, Map<String, Object> dataMap) throws Exception {
		Writer writer = new BufferedWriter(new OutputStreamWriter(os, encoding));
		getTemplate(name).process(dataMap, writer);
	}

	public static List<?> convertNullToStr(List<?> models) {
		models.forEach(e -> {
			Class<? extends Object> clazz = e.getClass();
			Field[] fileds = clazz.getDeclaredFields();
			for (Field f : fileds) {
				try {
					f.setAccessible(true);
					Object value = f.get(e);
					try {
						if (value == null) {
							f.set(e, "");
						}
					} catch (Exception e2) {
						// e2.printStackTrace();
					}
					if (value instanceof Collection) {
						List<?> obj = convertNullToStr((List<?>) value);
						f.set(e, obj);
					} else if (value instanceof Map) {

					} else if (value instanceof String) {
						f.set(e, ((String) value).replaceAll("<", "(").replaceAll(">", ")"));
					}
				} catch (Exception e1) {
					// e1.printStackTrace();
				}
			}
		});
		return models;
	}

	public static void main(String[] args) {
		ExportDoc maker = new ExportDoc("UTF-8");
		try {
			maker.exportDoc(new FileOutputStream(new File("C:\\Users\\0380009081\\Desktop\\Freemarket.doc")),
					"model_xml.ftl", getDataMap());
			System.out.println("ok");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}